<template>
  <div class="course-scores">
    <div class="scores-content">
      <!-- 成绩统计卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-title">总课程数</div>
            <div class="stat-value">{{ stats.totalCourses }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-title">学位课程数</div>
            <div class="stat-value">{{ stats.degreeCourses }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-title">平均成绩</div>
            <div class="stat-value">{{ stats.averageScore }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-title">学位课平均</div>
            <div class="stat-value">{{ stats.degreeAverageScore }}</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 成绩列表 -->
      <el-card class="scores-card">
        <template #header>
          <div class="card-header">
            <span>成绩详情</span>
            <div class="filters">
              <el-select v-model="selectedCourseType" placeholder="课程类型" @change="filterScores" style="width: 120px;">
                <el-option label="全部课程" value="" />
                <el-option label="学位课程" value="degree" />
                <el-option label="非学位课程" value="non-degree" />
              </el-select>
              <el-input
                v-model="searchKeyword"
                placeholder="搜索课程名称"
                style="width: 200px; margin-left: 10px;"
                clearable
                @input="filterScores"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
        </template>
        
        <el-table :data="filteredScores" style="width: 100%" v-loading="loading">
          <el-table-column prop="courseId" label="课程编号" width="120" />
          <el-table-column prop="courseName" label="课程名称" width="250" />
          <el-table-column prop="score" label="成绩" width="100">
            <template #default="scope">
              <span :class="getScoreClass(scope.row.score)">{{ scope.row.score }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="isDegreeCourse" label="课程类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isDegreeCourse ? 'success' : 'info'">
                {{ scope.row.isDegreeCourse ? '学位课程' : '非学位课程' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="成绩等级" width="100">
            <template #default="scope">
              <el-tag :type="getScoreTagType(scope.row.score)">
                {{ getScoreLevel(scope.row.score) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 成绩分析图表 -->
      <el-card class="analysis-card">
        <template #header>
          <span>成绩分析</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-container">
              <h4>成绩分布</h4>
              <div class="score-distribution">
                <div class="score-range">
                  <span>90-100分</span>
                  <el-progress :percentage="scoreDistribution.excellent" color="#67c23a" />
                </div>
                <div class="score-range">
                  <span>80-89分</span>
                  <el-progress :percentage="scoreDistribution.good" color="#409eff" />
                </div>
                <div class="score-range">
                  <span>70-79分</span>
                  <el-progress :percentage="scoreDistribution.average" color="#e6a23c" />
                </div>
                <div class="score-range">
                  <span>60-69分</span>
                  <el-progress :percentage="scoreDistribution.pass" color="#909399" />
                </div>
                <div class="score-range">
                  <span>60分以下</span>
                  <el-progress :percentage="scoreDistribution.fail" color="#f56c6c" />
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-container">
              <h4>课程类型分布</h4>
              <div class="course-type-distribution">
                <div class="type-item">
                  <span>学位课程</span>
                  <el-progress :percentage="courseTypeDistribution.degree" color="#67c23a" />
                </div>
                <div class="type-item">
                  <span>非学位课程</span>
                  <el-progress :percentage="courseTypeDistribution.nonDegree" color="#409eff" />
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

const loading = ref(false)

// 数据
const scores = ref([])
const searchKeyword = ref('')
const selectedCourseType = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 统计信息
const stats = ref({
  totalCourses: 0,
  degreeCourses: 0,
  averageScore: '0.0',
  degreeAverageScore: '0.0'
})

// 计算属性
const filteredScores = computed(() => {
  let result = scores.value
  
  if (searchKeyword.value) {
    result = result.filter(score => 
      score.courseName?.includes(searchKeyword.value) ||
      score.courseId?.includes(searchKeyword.value)
    )
  }
  
  if (selectedCourseType.value === 'degree') {
    result = result.filter(score => score.isDegreeCourse)
  } else if (selectedCourseType.value === 'non-degree') {
    result = result.filter(score => !score.isDegreeCourse)
  }
  
  return result
})

const scoreDistribution = computed(() => {
  const total = scores.value.length
  if (total === 0) return { excellent: 0, good: 0, average: 0, pass: 0, fail: 0 }
  
  const excellent = scores.value.filter(s => s.score >= 90).length
  const good = scores.value.filter(s => s.score >= 80 && s.score < 90).length
  const average = scores.value.filter(s => s.score >= 70 && s.score < 80).length
  const pass = scores.value.filter(s => s.score >= 60 && s.score < 70).length
  const fail = scores.value.filter(s => s.score < 60).length
  
  return {
    excellent: Math.round((excellent / total) * 100),
    good: Math.round((good / total) * 100),
    average: Math.round((average / total) * 100),
    pass: Math.round((pass / total) * 100),
    fail: Math.round((fail / total) * 100)
  }
})

const courseTypeDistribution = computed(() => {
  const total = scores.value.length
  if (total === 0) return { degree: 0, nonDegree: 0 }
  
  const degree = scores.value.filter(s => s.isDegreeCourse).length
  const nonDegree = total - degree
  
  return {
    degree: Math.round((degree / total) * 100),
    nonDegree: Math.round((nonDegree / total) * 100)
  }
})

const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 70) return 'score-average'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

const getScoreTagType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'primary'
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

const getScoreLevel = (score) => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 70) return '中等'
  if (score >= 60) return '及格'
  return '不及格'
}

const loadScores = async () => {
  const studentId = localStorage.getItem('studentId')
  if (!studentId) return
  
  loading.value = true
  try {
    const response = await axios.get(`/course-scores/student/${studentId}`)
    scores.value = response.data
    total.value = scores.value.length
    calculateStats()
  } catch (error) {
    console.error('加载成绩数据失败:', error)
    ElMessage.error('加载成绩数据失败')
  } finally {
    loading.value = false
  }
}

const calculateStats = () => {
  if (scores.value.length === 0) return
  
  const totalCourses = scores.value.length
  const degreeCourses = scores.value.filter(s => s.isDegreeCourse).length
  const totalScore = scores.value.reduce((sum, s) => sum + s.score, 0)
  const averageScore = totalScore / totalCourses
  
  const degreeScores = scores.value.filter(s => s.isDegreeCourse)
  const degreeTotalScore = degreeScores.reduce((sum, s) => sum + s.score, 0)
  const degreeAverageScore = degreeScores.length > 0 ? degreeTotalScore / degreeScores.length : 0
  
  stats.value = {
    totalCourses,
    degreeCourses,
    averageScore: averageScore.toFixed(1),
    degreeAverageScore: degreeAverageScore.toFixed(1)
  }
}

const filterScores = () => {
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

onMounted(() => {
  loadScores()
})
</script>

<style scoped>
.course-scores {
  max-width: 1200px;
  margin: 0 auto;
}

.scores-content {
  max-width: 1200px;
  margin: 0 auto;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.scores-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filters {
  display: flex;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.analysis-card {
  margin-bottom: 20px;
}

.chart-container {
  padding: 20px;
}

.chart-container h4 {
  margin-bottom: 20px;
  color: #333;
}

.score-distribution .score-range,
.course-type-distribution .type-item {
  margin-bottom: 15px;
}

.score-distribution .score-range span,
.course-type-distribution .type-item span {
  display: inline-block;
  width: 80px;
  font-size: 14px;
  color: #666;
}

.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-average {
  color: #e6a23c;
  font-weight: bold;
}

.score-pass {
  color: #909399;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}
</style> 